package com.malbbmsomanager;
/************PDADBWebServiceBBM -> Live Environment************/
/************PDADBWebServiceBestBuy - Web Server**********************/
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.malbbmsomanager.R;
import com.malbbmsomanager.backup.DM_BBM_Excel_Generator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class DM_BBM_Settings extends Activity {
	private static final String TAG = null;
	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private String DBNAME = "dminvoicemanagerbbm.db";
	// Master Tables BBM
	private String FDEBTOR_TABLE = "fDebtor";
	private String FTAXDET_TABLE = "FtaxDet";
	private String FBRAND_TABLE = "FBrand";
	private String FITEMS_TABLE = "FItems";
	private String FCURRENCY_TABLE = "fCurrency";
	private String FSALREP_TABLE = "fSalRep";
	private String FCOMPANYBRANCH_TABLE = "FCompanyBranch";
	private String FCOMPANYSETTINGS_TABLE = "fCompanySetting";
	private String FLOCATION_TABLE = "fLocation";
	private String FDDBNOTE_TABLE = "fddbnote";
	private String FAREA_TABLE = "fArea";
	private String FITEMFREQTY_TABLE = "fItemFreeQty";
	private String FITEMPRI_TABLE = "fItemPri";
	private String FTAXHED_TABLE = "fTaxHed";
	private String FTAX_TABLE = "fTax";
	private String FCONTROL_TABLE = "fControlResult";
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	private String SERVER_DETAILS = "serverinfo";
	private String FDEBTAX_TABLE = "fDebTax";
	private String FCOMPANYDM_TABLE = "fCompanyDM";
	private String FGLFACC_TABLE = "fglfacc";
	private String FBANK_TABLE = "fbank";

	private SQLiteDatabase mydb;
	// FDealer
	private CountDownTimer mCountDown;
	EditText etsettingsuser, etsettingsrepcode, etsettingslocationcode,
			etsettingsareacode, etsettingsroutecode, etsettingsdealcode,
			etsettingssdb, etsettingsrepprefix, etCurrentUrl;
	static// Spinner element
	String currentServerDbName;
	String currentSalesRepRoute;
	String currentSalesRep;
	String selectedServerDB;
	String serverDbName = "0";
	String repRoute = "0";
	AlertDialog SynchDetails = null;
	String TagId, fromLocCode, RecordIdFI;
	private Spinner serverDatbaeSpinner, serverFRouteSpinner, salesRepSpinner;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerDB;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerRoute;
	private ArrayAdapter<CharSequence> m_adapterForSpinnerSalesRep;
	String CurrentUser, connectionURL, exportFileNamePrefix = "dbback";
	EditText etsettingsprintermac;
	int stYear = 2000;
	int arrayLength = 0;
	int NetFail = 0;
	final private static int DIALOG_SYNC_SUCCESS = 1;
	AlertDialog InvoiceHeaderAlert = null;
	Button editCurrentServerURL, synchServerDb, processbackup, generatePDF,
			generateBackup;
	// flag for Internet connection status
	Boolean isInternetPresent = false;
	// Connection detector class
	DM_BBM_ConnectionDetector cd;

	StringBuilder sb, sbNew;
	String result, resultNew, FresultB;
	InputStream isNew;
	JSONArray jArray;

	// URL to get JSON Array
	private static String url = "http://123.231.13.199:1025/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemLocFreeQty/mobile123/"
			+ currentServerDbName;
	// JSON Node Names
	private static final String TAG_USER = "WordID";
	private static final String TAG_ID = "LID";
	private static final String TAG_NAME = "NID";
	private static final String TAG_EMAIL = "word";
	JSONArray user = null;

	HttpURLConnection con = null;
	InputStream is = null;

	public void DataXmlExporter(SQLiteDatabase mydb) {
		this.mydb = mydb;
	}

	public void SyncCompleteAccept(View view) {
		Intent myIntent = new Intent(view.getContext(), DM_BBM_Settings.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "RELOAD");
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void BackToMainMenu(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		// myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}

	public void btnExitSettings(View view) {

		if (TagId.equals("SUPPER")) {
			Intent myIntent = new Intent(view.getContext(),
					DM_BBM_InvoiceMainActivity.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivityForResult(myIntent, 0);
			finish();
			return;
		} else {
			Intent myIntent = new Intent(view.getContext(),
					DM_BBM_InvoiceMainActivity.class);
			myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);
			// myIntent.putExtra("TAGID", "SALES");
			startActivityForResult(myIntent, 0);
			finish();
			return;
		}
	}

	public void btnSaveUrlProperties(View view) {
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUdateUserPrinterSetting = null;
		try {
			curUdateUserPrinterSetting = mydb.query(USER_SETTINGS, null,
					"username = '" + CurrentUser + "'", null, null, null, null);
		} catch (Exception e) {
		}

		if (curUdateUserPrinterSetting != null) {
			if (curUdateUserPrinterSetting.getCount() > 0) {
				while (curUdateUserPrinterSetting.moveToNext()) {
					if (etsettingsuser.length() == 0) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SALES REP");
						// Setting Dialog Message
						alertDialog.setMessage("Select User From The List.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);

					} else {
						String CurrentUserId = curUdateUserPrinterSetting
								.getString(0);
						CurrentUser = curUdateUserPrinterSetting.getString(1);
						ContentValues userPrinter = new ContentValues();
						userPrinter.put("username", etsettingsuser.getText()
								.toString().toUpperCase());
						userPrinter.put("lrepprefix", etsettingsrepprefix
								.getText().toString());
						userPrinter.put("lreploccode", etsettingslocationcode
								.getText().toString());
						userPrinter.put("locationCode", etsettingslocationcode
								.getText().toString());
						userPrinter.put("serverDbName", etsettingssdb.getText()
								.toString());
						userPrinter.put("printerMac", etsettingsprintermac
								.getText().toString());
						userPrinter.put("repareacode", etsettingsareacode
								.getText().toString());
						userPrinter.put("repdealcode", etsettingsdealcode
								.getText().toString());
						userPrinter.put("reproutecode", etsettingsroutecode
								.getText().toString());
						mydb.update(USER_SETTINGS, userPrinter, "_id ='1'",
								null);

						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("UPDATE SETINGS");
						// Setting Dialog Message
						alertDialog
								.setMessage("User Settings Updated Successfully.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
										exitFromSettings();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
					}
				}
			} else {
				try {
					ContentValues userPrinter = new ContentValues();
					userPrinter.put("username", etsettingsuser.getText()
							.toString().toUpperCase());
					userPrinter.put("lrepprefix", etsettingsrepprefix.getText()
							.toString());
					userPrinter.put("lreploccode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("locationCode", etsettingslocationcode
							.getText().toString());
					userPrinter.put("serverDbName", etsettingssdb.getText()
							.toString());
					userPrinter.put("printerMac", etsettingsprintermac
							.getText().toString());
					userPrinter.put("repareacode", etsettingsareacode.getText()
							.toString());
					userPrinter.put("repdealcode", etsettingsdealcode.getText()
							.toString());
					userPrinter.put("reproutecode", etsettingsroutecode
							.getText().toString());
					mydb.update(USER_SETTINGS, userPrinter, "_id ='1'", null);

				} catch (Exception e) {
					// Toast.makeText(this, e.toString(),
					// Toast.LENGTH_LONG).show();
				}
			}
		}
		curUdateUserPrinterSetting.close();
		mydb.close();
	}

	protected void exitFromSettings() {
		// TODO Auto-generated method stub
		Intent myIntent = new Intent(this, DM_BBM_InvoiceMainActivity.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		// myIntent.putExtra("TAGID", "SALES");
		startActivityForResult(myIntent, 0);
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_settings);

		Bundle bundle = getIntent().getExtras();
		TagId = bundle.getString("TAGID");

		// Spinner element
		serverDatbaeSpinner = (Spinner) findViewById(R.id.spinnerServerDB);
		serverFRouteSpinner = (Spinner) findViewById(R.id.salesrepRouteList);
		salesRepSpinner = (Spinner) findViewById(R.id.salesrepList);

		etsettingsuser = (EditText) findViewById(R.id.etsettingsuser);
		etsettingsrepcode = (EditText) findViewById(R.id.etsettingsrepcode);
		etsettingsrepprefix = (EditText) findViewById(R.id.etsettingsrepprefix);
		etsettingslocationcode = (EditText) findViewById(R.id.etsettingslocationcode);
		etsettingsareacode = (EditText) findViewById(R.id.etsettingsareacode);
		etsettingsroutecode = (EditText) findViewById(R.id.etsettingsroutecode);
		etsettingsdealcode = (EditText) findViewById(R.id.etsettingsdealcode);
		etsettingssdb = (EditText) findViewById(R.id.etsettingssdb);
		etsettingsprintermac = (EditText) findViewById(R.id.etsettingsprintermac);
		etCurrentUrl = (EditText) findViewById(R.id.printcurrenturl);
		editCurrentServerURL = (Button) findViewById(R.id.editcurrentserverURL);
		processbackup = (Button) findViewById(R.id.processbackup);
		generatePDF = (Button) findViewById(R.id.generatePDF);
		generateBackup = (Button) findViewById(R.id.generateBackup);

		cd = new DM_BBM_ConnectionDetector(getApplicationContext());
		getConnectionUrl();
		displayCurrentSettings();
		loadServerDataBase();
		// loadToMainStoreRouteSpinner();
		loadToMainStoreSalesRepSpinner();

		editCurrentServerURL.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Properties.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		generateBackup.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Excel_Generator.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
			}
		});

		generatePDF.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

			}
		});

		synchServerDb = (Button) findViewById(R.id.synchServerDb);
		synchServerDb.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					logYearsList();
					logMonthList();
					if (serverDbName.equals("0")) {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("SELECT SERVER DB");
						// Setting Dialog Message
						alertDialog
								.setMessage("Select Server Database From List.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					} else {
						UpdateUserSettings();
						synchMasterTableData();
					}

				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_BBM_Settings.this,
							"No Internet Connection",
							"You don't have internet connection.", false);
				}

			}

		});

		if (TagId.equals("SALES")) {
			serverDatbaeSpinner.setEnabled(false);
			salesRepSpinner.setEnabled(false);
			synchServerDb.setEnabled(false);
			editCurrentServerURL.setEnabled(false);
		}

		serverDatbaeSpinner.setAdapter(m_adapterForSpinnerDB);
		serverDatbaeSpinner
				.setOnItemSelectedListener(new OnItemSelectedListener() {
					public void onItemSelected(AdapterView<?> parent,
							View view, int position, long id) {
						currentServerDbName = serverDatbaeSpinner
								.getSelectedItem().toString();
						if (!(currentServerDbName.equals("SELECT SERVER DB"))) {

							SQLiteDatabase mydb;
							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);

							Cursor getfromloccur = null;
							try {
								getfromloccur = mydb.query(SERVER_DB_LIST,
										null, "sdbname='" + currentServerDbName
												+ "'", null, null, null, null,
										null);
							} catch (Exception e) {

							}
							if (getfromloccur != null) {
								if (getfromloccur.getCount() > 0) {

									while (getfromloccur.moveToNext()) {
										fromLocCode = getfromloccur
												.getString(0);
										serverDbName = getfromloccur
												.getString(1);
										etsettingssdb
												.setText(currentServerDbName);
									}
								}
								getfromloccur.close();
							}

						} else {
							serverDbName = "0";
						}

					}

					public void onNothingSelected(AdapterView<?> parent) {
					}
				});

		// ===============Load SalesRep Details=========================
		salesRepSpinner.setAdapter(m_adapterForSpinnerSalesRep);
		salesRepSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				currentSalesRep = salesRepSpinner.getSelectedItem().toString();
				Log.v(TAG, "currentSalesRep:" + currentSalesRep);
				if (!(currentSalesRep.equals("SELECT SALESREP"))) {

					SQLiteDatabase mydb;
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);

					Cursor getSalesRepDet = null;
					try {
						String querySalRep = "SELECT * FROM fSalRep Where RepName = '"
								+ currentSalesRep.trim() + "'";
						getSalesRepDet = mydb.rawQuery(querySalRep, null);

					} catch (Exception e) {

					}
					if (getSalesRepDet != null) {
						if (getSalesRepDet.getCount() > 0) {
							String RepPrefix = null;
							while (getSalesRepDet.moveToNext()) {
								String strRepCode = getSalesRepDet.getString(1);
								String strRepName = getSalesRepDet.getString(2);
								String strRepIdNo = getSalesRepDet.getString(3);
								String strRepTele = getSalesRepDet.getString(7);
								String strRepMobil = getSalesRepDet.getString(8);
								RepPrefix = getSalesRepDet.getString(14);
								
								if(RepPrefix  != null){
									RepPrefix = getSalesRepDet.getString(14);
								}
								else {
									RepPrefix = "A";
								}

								etsettingsuser.setText(strRepName);
								etsettingsrepcode.setText(strRepCode);
								etsettingsrepprefix.setText(RepPrefix);
								etsettingslocationcode.setText(strRepTele);
								etsettingsareacode.setText(strRepMobil);
								etsettingsdealcode.setText(strRepIdNo);
							}
						} else {
							etsettingsuser.setText("");
							etsettingsrepprefix.setText("");
							etsettingsrepcode.setText("");
							etsettingslocationcode.setText("");
							etsettingsareacode.setText("");
							etsettingsdealcode.setText("");
							etsettingsroutecode.setText("");
							final AlertDialog alertDialog = new AlertDialog.Builder(
									DM_BBM_Settings.this).create();
							// Setting Dialog Title
							alertDialog.setTitle("UNAUTHORIZED SALES REP");
							// Setting Dialog Message
							alertDialog
									.setMessage("Selected Sales Rep Not Authorized.Select Another Sales Rep.");
							// Setting Icon to Dialog
							alertDialog.setIcon(R.drawable.warning);
							// Setting OK Button
							alertDialog.setButton("OK",
									new DialogInterface.OnClickListener() {
										public void onClick(
												DialogInterface dialog,
												int which) {
											alertDialog.dismiss();
											return;
										}
									});
							// Showing Alert Message
							alertDialog.show();
							alertDialog.setCanceledOnTouchOutside(false);
							return;
						}
						getSalesRepDet.close();
					} else {
						final AlertDialog alertDialog = new AlertDialog.Builder(
								DM_BBM_Settings.this).create();
						// Setting Dialog Title
						alertDialog.setTitle("UNAUTHORIZED SALES REP");
						// Setting Dialog Message
						alertDialog
								.setMessage("Selected Sales Rep Not Authorized.Select Another Sales Rep.");
						// Setting Icon to Dialog
						alertDialog.setIcon(R.drawable.warning);
						// Setting OK Button
						alertDialog.setButton("OK",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
										alertDialog.dismiss();
										return;
									}
								});
						// Showing Alert Message
						alertDialog.show();
						alertDialog.setCanceledOnTouchOutside(false);
						return;
					}

				} else {
					repRoute = "0";
				}

			}

			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

		try {

			mydb.execSQL("create table if not exists "
					+ YEARS_LIST
					+ "(year_id integer primary key autoincrement,yearname text not null);");

			mydb.execSQL("create table if not exists "
					+ MONTH_LIST
					+ "(month_id integer primary key autoincrement,monthindex text not null,monthname text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DETAILS
					+ "(server_id integer primary key autoincrement,serverurl text not null,portval text not null);");

			mydb.execSQL("create table if not exists "
					+ SERVER_DB_LIST
					+ "(sdb_id integer primary key autoincrement,sdbname text not null);");

			mydb.execSQL("create table if not exists "
					+ USER_SETTINGS
					+ "(_id integer primary key autoincrement,username text not null,lrepprefix text not null,lreploccode text not null,currentStOrdNo text not null,locationCode text not null,receiptCode text not null,serverDbName text not null,printerMac text not null,repareacode text not null,repdealcode text not null,reproutecode text not null);");

			// Create Master Tables
			mydb.execSQL("create table if not exists "
					+ FDEBTOR_TABLE
					+ "(_id integer primary key autoincrement,DebCode text not null,DebName text not null,DebAdd1 text not null,DebAdd2 text not null,DebAdd3 text not null,DebTele text not null,DebMob text not null,DelEmail text not null,Status text not null,DelPersn text not null,TaxReg text not null,RecordId text not null,AreaCode text not null,CrdPeriod text not null,CrdLimit text not null,RepCode text not null,PrilCode text not null,AreaName text not null);");

			mydb.execSQL("create table if not exists "
					+ FTAXDET_TABLE
					+ "(ftaxdet_id integer primary key autoincrement,TaxComCode  text not null,TaxCode  text not null,TaxRate  text not null,TaxMode  text not null,TaxSeq  text not null,RecordId  text not null);");

			mydb.execSQL("create table if not exists "
					+ FBRAND_TABLE
					+ "(fbrand_id integer primary key autoincrement,BrandCode text not null,BrandName text not null,AddUser text not null,AddDate text not null,AddMach text not null,RecordId text not null);");

			mydb.execSQL("create table if not exists "
					+ FITEMS_TABLE
					+ "(_id integer primary key autoincrement,ItemCode text not null,ItemName text not null,BrandCode text not null,AvgPrice text not null,PrilCode text not null,packing text not null,PackSize text not null,TaxComCode text not null,ReOrderQty text not null,AddDate text not null,RecordId text not null,PurDesc text not null,TypeCode text not null,UnitCode text not null,ReOrderLvl text not null,CatCode text not null,cosacc text not null,GroupCode text not null,itemsummary text not null,ItemStatus text not null,FreeItems text not null);");

			mydb.execSQL("create table if not exists "
					+ FDDBNOTE_TABLE
					+ "(_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,BAmt text not null,DebCode text not null,RecordId text not null,ManuRef text not null,Curcode text not null,Amt text not null,Totbal text not null,Remarks text not null,RepCode text not null);");

			mydb.execSQL("create table if not exists "
					+ FCURRENCY_TABLE
					+ "(fcur_id integer primary key autoincrement,CurCode text not null,CurDesc text not null,fromrate text not null,torate text not null,AddUser text not null,AddDate text not null,AddMach text not null,recordid  text not null);");

			mydb.execSQL("create table if not exists "
					+ FSALREP_TABLE
					+ "(fsalrep_id integer primary key autoincrement,RepCode text not null,RepName text not null,RepIdNo text not null,RepAdd1 text not null,RepAdd2 text not null,RepAdd3 text not null,RepTele text not null,RepMobil text not null,RepEMail text not null,AddUser text not null,AddMach text not null,AddDate text not null,RecordId  text not null,RepPrefix text not null);");

			mydb.execSQL("create table if not exists "
					+ FCOMPANYSETTINGS_TABLE
					+ "(fcomset_id integer primary key autoincrement,cSettingsCode text not null,cSettingGrp text not null,cLocationChar text not null,cCharVal text not null,nNumVal text not null,cRemarks text not null,nType text not null,bUpdateFlag text not null,cCompanyCode text not null,recordid text not null);");

			mydb.execSQL("create table if not exists "
					+ FLOCATION_TABLE
					+ "(floc_id integer primary key autoincrement text not null,LocCode text not null,LocName text not null,TeleNo text not null,FaxNo text not null,EMail text not null,LoctCode text not null,Contact text not null,Address1 text not null,Address2 text not null,Address3 text not null,AddUser text not null,AddDate text not null,AddMach text not null,RecordId text not null,prefix text not null,cSettingsCode text not null,ProfCen text not null,cSettingsCde2 text not null,CostCode text not null,AccCode text not null);");

			mydb.execSQL("create table if not exists "
					+ FITEMFREQTY_TABLE
					+ "(_id integer primary key autoincrement,ItemCode text not null,FreeQty text not null);");
		} catch (Exception e) {
		}

	}

	private void writeToFile(String xmlString, String exportFileName)
			throws IOException {
		File dir = new File(Environment.getExternalStorageDirectory(), DBNAME);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(dir, exportFileName);
		file.createNewFile();

		ByteBuffer buff = ByteBuffer.wrap(xmlString.getBytes());
		FileChannel channel = new FileOutputStream(file).getChannel();
		try {
			channel.write(buff);
		} finally {
			if (channel != null)
				channel.close();
		}
	}

	// Alert View Validating Network Connection
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				new DownloadAdministrative().execute();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					etCurrentUrl.setText(connectionURL);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}
		mydb.close();
	}

	private void loadToMainStoreSalesRepSpinner() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerSalesRep = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerSalesRep
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curRoute = null;
		try {
			curRoute = mydb.query(FSALREP_TABLE, null, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (curRoute != null) {
			if (curRoute.getCount() > 0) {
				m_adapterForSpinnerSalesRep.add("SELECT SALESREP");
				while (curRoute.moveToNext()) {
					m_adapterForSpinnerSalesRep.add(curRoute.getString(2));
				}
			}
			curRoute.close();
		}
		mydb.close();

	}

	private void logYearsList() {
		// TODO Auto-generated method stub
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			for (int i = stYear; i <= 2033; i++) {
				ContentValues newYearRaw = new ContentValues();
				String strYear = Integer.toString(stYear);
				newYearRaw.put("yearname", strYear);
				mydb.insert(YEARS_LIST, null, newYearRaw);
				stYear = stYear + 1;
			}
		} catch (Exception e) {
			// Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
		}
		mydb.close();
	}

	private void logMonthList() {
		// TODO Auto-generated method stub
		try {
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('1','January')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('2','February')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('3','March')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('4','April')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('5','May')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('6','June')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('7','July')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('8','August')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('9','September')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('10','October')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('11','November')");
			mydb.execSQL("INSERT INTO " + MONTH_LIST
					+ "(monthindex, monthname) VALUES('12','December')");
			mydb.close();

		} catch (Exception e) {
			Toast.makeText(getApplicationContext(),
					"Error in inserting into table", Toast.LENGTH_LONG);
		}
	}

	private void loadServerDataBase() {
		// TODO Auto-generated method stub
		m_adapterForSpinnerDB = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item);
		m_adapterForSpinnerDB
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curServerDB = null;
		try {
			curServerDB = mydb.query(SERVER_DB_LIST, null, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (curServerDB != null) {
			if (curServerDB.getCount() > 0) {
				m_adapterForSpinnerDB.add("SELECT SERVER DB");
				while (curServerDB.moveToNext()) {
					m_adapterForSpinnerDB.add(curServerDB.getString(1));
				}
			}
			curServerDB.close();
		}
		mydb.close();
	}

	// Synch Master table data for the application
	protected void synchMasterTableData() {
		// TODO Auto-generated method stub
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		new DownloadAdministrative().execute();
	}

	/*// DownloadJSON AsyncTask
		private class DownloadAdministrative extends AsyncTask<Void, Void, Void> {
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				// Create a progressdialog
				mProgressDialog = new ProgressDialog(DM_BBM_Settings.this);
				mProgressDialog.setMax(100);
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setCancelable(false);
				// Set progressdialog title
				mProgressDialog.setTitle("Downloading Details");
				// Set progressdialog message
				mProgressDialog.setMessage("Loading Details...");
				mProgressDialog.setIndeterminate(false);
				// Show progressdialog
				mProgressDialog.show();
			}
			@Override
			protected Void doInBackground(Void... params) {
				// TODO Auto-generated method stub
				try {
					
					try{
						 mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
						 mydb.execSQL("DROP TABLE IF EXISTS fddbnote");
						 mydb.execSQL("create table if not exists "
									+ FDDBNOTE_TABLE
									+ "(_id integer primary key autoincrement,RefNo text not null,TxnDate text not null,BAmt text not null,DebCode text not null,RecordId text not null,ManuRef text not null,Curcode text not null,Amt text not null,Totbal text not null,Remarks text not null,RepCode text not null);");
		
					}
					catch(Exception e){
						
					}
					
					DefaultHttpClient httpClient = new DefaultHttpClient();
					try {
						HttpResponse response = httpClient
								.execute(new HttpGet("http://123.231.13.199:1025/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fddbnote/mobile123/BBMPDA"));
						InputStream is = response.getEntity().getContent();
						if (is != null) {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";

							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							result = sb.toString();

							String FresultA = result.replace(
									"{\"fDdbNoteResult\":[{", "[{");
							FresultB = FresultA.replace("}]}", "}]");
							// convert String into InputStream
							isNew = new ByteArrayInputStream(FresultB.getBytes());

						}
						if (isNew != null) {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(isNew, "iso-8859-1"), 8);
							sbNew = new StringBuilder();
							sbNew.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sbNew.append(line + "\n");
							}
							resultNew = sbNew.toString();
						}

						jArray = new JSONArray(resultNew);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							String Amt = json_data.getString("Amt");
							String BAmt = json_data.getString("BAmt");
							String CurCode = json_data.getString("CurCode");
							String DebCode = json_data.getString("DebCode");
							String ManuRef = json_data.getString("ManuRef");
							String RecordId = json_data.getString("RecordId");
							String RefNo = json_data.getString("RefNo");
							String Remarks = json_data.getString("Remarks");
							String RepCode = json_data.getString("RepCode");
							String TotBal = json_data.getString("TotBal");
							String TxnDate = json_data.getString("TxnDate");
							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);
							ContentValues newrowfbranch = new ContentValues();
							Cursor fCompanyBranch = null;
							try {
								fCompanyBranch = mydb.query(FCOMPANYBRANCH_TABLE,
										null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
							} catch (Exception e) {
							}
							if (fCompanyBranch != null) {
								if (fCompanyBranch.getCount() >= 1) {
									Log.v(TAG, "Excisting fCompanyBranch(15)");

								} else {
									Log.v(TAG, "Insert fCompanyBranch(15):"
											+ RecordId);
									ContentValues newrowfddbnote = new ContentValues();
									newrowfddbnote.put("RefNo",RefNo.trim());
									newrowfddbnote.put("TxnDate", TxnDate.trim());
									newrowfddbnote.put("BAmt", BAmt.trim());
									newrowfddbnote.put("DebCode", DebCode.trim());
									newrowfddbnote.put("RecordId", RecordId.trim());
									newrowfddbnote.put("ManuRef", ManuRef.trim());
									newrowfddbnote.put("Curcode", CurCode.trim());
									newrowfddbnote.put("Amt", Amt.trim());
									newrowfddbnote.put("Totbal", TotBal.trim());
									newrowfddbnote.put("Remarks", Remarks.trim());
									newrowfddbnote.put("RepCode", RepCode.trim());
									mydb.insert(FDDBNOTE_TABLE, null, newrowfddbnote);
									fCompanyBranch.close();
									mydb.close();
								}
							}
							fCompanyBranch.close();
							mydb.close();
						}

					} catch (Exception e) {
						e.printStackTrace();
						Log.d("", "exception1 : " + e);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.d("", "exception2 : " + e);
				}

				return null;
			}
			@Override
			protected void onPostExecute(Void args) {
					mProgressDialog.dismiss();
					// arrayLength = 100;

			}
		}
*/
	
	
	// DownloadJSON AsyncTask
	private class DownloadAdministrative extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_Settings.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		// *****************Background Process**************************
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			// *****Download Server Databases*****
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));
				String line = readerfdblist.readLine();
				JSONObject jsonResponse = new JSONObject(line);
				JSONArray jsonArray = jsonResponse
						.getJSONArray("GetdatabaseNamesResult");
				for (int i = 0; i < jsonArray.length(); i++) {
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowdblist = new ContentValues();
					Cursor sdblistrows = null;
					try {
						sdblistrows = mydb.query(SERVER_DB_LIST, null,
								"sdbname ='" + sdbname + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (sdblistrows != null) {
						if (sdblistrows.getCount() >= 1) {
							while (sdblistrows.moveToNext()) {
								Log.v(TAG, "Excisting fServer DB 1 :" + sdbname);
							}
						} else {
							Log.v(TAG, "INSERT SERVER DB(1):" + i + "="
									+ sdbname.trim());
							newrowdblist.put("sdbname", sdbname.trim());
							mydb.insert(SERVER_DB_LIST, null, newrowdblist);
							sdblistrows.close();
							mydb.close();
						}
					}
					sdblistrows.close();
					mydb.close();
				}
				arrayLength = 4;//4
				progressHandler.sendMessage(progressHandler.obtainMessage());
				readerfdblist.close();

			} catch (Exception e) {
			}

			// *****************Download Free Items Quentity**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemLocFreeQty/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemLocFreeQtyResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String FreeQty = json_data.getString("FreeQty");
						String ItemCode = json_data.getString("ItemCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues insertItemFreeQty = new ContentValues();
						Cursor readItemFreeQty = null;
						try {
							readItemFreeQty = mydb.query(FITEMFREQTY_TABLE,
									null, "ItemCode ='" + ItemCode + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (readItemFreeQty != null) {
							if (readItemFreeQty.getCount() >= 1) {
								while (readItemFreeQty.moveToNext()) {
									Log.v(TAG, "Excit Free Qty (2):" + ItemCode);
								}
							} else {
								Log.v(TAG, "INSERT FreeQty(2):" + i + " = "
										+ ItemCode);
								insertItemFreeQty
										.put("FreeQty", FreeQty.trim());
								insertItemFreeQty.put("ItemCode",
										ItemCode.trim());
								mydb.insert(FITEMFREQTY_TABLE, null,
										insertItemFreeQty);
								readItemFreeQty.close();
							}
						}
						readItemFreeQty.close();
						mydb.close();

					}
					arrayLength = 6;//10
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download FbrandResult Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FBrand/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FbrandResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String BrandCode = json_data.getString("BrandCode");
						String BrandName = json_data.getString("BrandName");
						String AddUser = json_data.getString("AddUser");
						String AddMach = json_data.getString("AddMach");
						String RecordId = json_data.getString("RecordId");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfBrand = new ContentValues();
						Cursor fBrandrows = null;
						try {
							fBrandrows = mydb.query(FBRAND_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fBrandrows != null) {
							if (fBrandrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fBrand (3)");
							} else {
								Log.v(TAG, "INSERT fBrand(3) :" + i + " = "
										+ RecordId.trim());
								newrowfBrand.put("BrandCode", BrandCode.trim());
								newrowfBrand.put("BrandName", BrandName.trim());
								newrowfBrand.put("AddUser", AddUser.trim());
								newrowfBrand.put("AddDate", "");
								newrowfBrand.put("AddMach", AddMach.trim());
								newrowfBrand.put("RecordId", RecordId.trim());
								mydb.insert(FBRAND_TABLE, null, newrowfBrand);
								fBrandrows.close();
								mydb.close();
							}
						}
						fBrandrows.close();
						mydb.close();
					}
					arrayLength = 4;//14
					progressHandler.sendMessage(progressHandler.obtainMessage());
					

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download FCompanysetting Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCompanysetting/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCompanySettingResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCode = json_data
								.getString("cSettingsCode");
						String cSettingGrp = json_data.getString("cSettingGrp");
						String cLocationChar = json_data
								.getString("cLocationChar");
						String cCharVal = json_data.getString("cCharVal");
						String nNumVal = json_data.getString("nNumVal");
						String cRemarks = json_data.getString("cRemarks");
						String nType = json_data.getString("nType");
						String bUpdateFlag = json_data.getString("bUpdateFlag");
						String cCompanyCode = json_data
								.getString("cCompanyCode");
						String recordid = json_data.getString("recordid");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCompanySetting = new ContentValues();
						Cursor fCompanySettingrows = null;
						try {
							fCompanySettingrows = mydb.query(
									FCOMPANYSETTINGS_TABLE, null, "recordid ='"
											+ recordid.trim() + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (fCompanySettingrows != null) {
							if (fCompanySettingrows.getCount() >= 1) {
								Log.v(TAG, "Excisting FCompanysetting (4)");
							} else {
								Log.v(TAG, "INSERT FCompanysetting(4) :" + i
										+ " = " + cSettingsCode.trim());
								newrowfCompanySetting.put("cSettingsCode",
										cSettingsCode.trim());
								newrowfCompanySetting.put("cSettingGrp",
										cSettingGrp.trim());
								newrowfCompanySetting.put("cLocationChar",
										cLocationChar.trim());
								newrowfCompanySetting.put("cCharVal",
										cCharVal.trim());
								newrowfCompanySetting.put("nNumVal",
										nNumVal.trim());
								newrowfCompanySetting.put("cRemarks",
										cRemarks.trim());
								newrowfCompanySetting.put("nType ",
										nType.trim());
								newrowfCompanySetting.put("bUpdateFlag",
										bUpdateFlag.trim());
								newrowfCompanySetting.put("cCompanyCode",
										cCompanyCode.trim());
								newrowfCompanySetting.put("recordid",
										recordid.trim());
								mydb.insert(FCOMPANYSETTINGS_TABLE, null,
										newrowfCompanySetting);
								fCompanySettingrows.close();
								mydb.close();
							}
						}
					
						fCompanySettingrows.close();
						mydb.close();
					}
					arrayLength = 3;//17
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fCurrencyResult**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCurrency/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCurrencyResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String CurCode = json_data.getString("CurCode");
						String CurDesc = json_data.getString("CurDesc");
						String RecordId = json_data.getString("RecordId");
						String fromrate = json_data.getString("fromrate");
						String torate = json_data.getString("torate");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCurrency = new ContentValues();
						Cursor fCurrencyrows = null;
						try {
							fCurrencyrows = mydb.query(FCURRENCY_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCurrencyrows != null) {
							if (fCurrencyrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fCurrency (5)");
							} else {
								Log.v(TAG, "INSERT fCurrency (5) :" + i + "="
										+ RecordId.trim());
								newrowfCurrency.put("CurCode", CurCode.trim());
								newrowfCurrency.put("CurDesc", CurDesc.trim());
								newrowfCurrency
										.put("fromrate", fromrate.trim());
								newrowfCurrency.put("torate", torate.trim());
								newrowfCurrency.put("AddUser", AddUser.trim());
								newrowfCurrency.put("AddDate", AddDate.trim());
								newrowfCurrency.put("AddMach", AddMach.trim());
								newrowfCurrency
										.put("recordid", RecordId.trim());
								mydb.insert(FCURRENCY_TABLE, null,
										newrowfCurrency);
								fCurrencyrows.close();
								mydb.close();
							}
						}
					
						fCurrencyrows.close();
						mydb.close();
					}
					arrayLength = 4;//21
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download Debtor Detaails**************
			try {
				Log.e("", "Read URL 1: " + url);
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/Fdebtor/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FdebtorResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String DebCode = json_data.getString("DebCode");
						String DebName = json_data.getString("DebName");
						String DebAdd1 = json_data.getString("DebAdd1");
						String DebAdd2 = json_data.getString("DebAdd2");
						String DebAdd3 = json_data.getString("DebAdd3");
						String DebTele = json_data.getString("DebTele");
						String DebMob = json_data.getString("DebMob");
						String Status = json_data.getString("Status");
						String DelPersn = json_data.getString("DelPersn");
						String DelEmail = json_data.getString("DelEmail");
						String AreaCode = json_data.getString("AreaCode");
						String CrdPeriod = json_data.getString("CrdPeriod");
						String CrdLimit = json_data.getString("CrdLimit");
						String RepCode = json_data.getString("RepCode");
						String TaxReg = json_data.getString("TaxReg");
						String PrilCode = json_data.getString("PrilCode");
						String RecordId = json_data.getString("recordid");


						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfdebtord = new ContentValues();
						Cursor fdebtorduserrows = null;
						try {
							fdebtorduserrows = mydb.query(FDEBTOR_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fdebtorduserrows != null) {
							if (fdebtorduserrows.getCount() >= 1) {
								Log.v(TAG, "Excisting Debtor(6) :");
							} else {
								Log.v(TAG,"INSERT Debtor(6) :" + RecordId.trim());
								newrowfdebtord.put("DebCode", DebCode.trim());
								newrowfdebtord.put("DebName", DebName.trim());
								newrowfdebtord.put("DebAdd1", DebAdd1.trim());
								newrowfdebtord.put("DebAdd2", DebAdd2.trim());
								newrowfdebtord.put("DebAdd3", DebAdd3.trim());
								newrowfdebtord.put("DebTele", DebTele.trim());
								newrowfdebtord.put("DebMob", DebMob.trim());
								newrowfdebtord.put("DelEmail", DelEmail.trim());
								newrowfdebtord.put("Status", Status.trim());
								newrowfdebtord.put("DelPersn", DelPersn.trim());
								newrowfdebtord.put("TaxReg", TaxReg.trim());
						        newrowfdebtord.put("RecordId", RecordId.trim());
						        newrowfdebtord.put("AreaCode", AreaCode.trim());
								newrowfdebtord.put("CrdPeriod", CrdPeriod.trim());
								newrowfdebtord.put("CrdLimit", CrdLimit.trim());
								newrowfdebtord.put("RepCode", RepCode.trim());
								newrowfdebtord.put("PrilCode", PrilCode.trim());
								newrowfdebtord.put("AreaName", "");
								
								mydb.insert(FDEBTOR_TABLE, null, newrowfdebtord);
								fdebtorduserrows.close();
								mydb.close();
							}
						}
						
						fdebtorduserrows.close();
						mydb.close();
					}
					arrayLength = 7;//28
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fItems Result**************
			try {
				Log.e("", "Read URL 1: " + url);
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItems/mobile123/"
											+ currentServerDbName));

					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemsResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String ItemCode = json_data.getString("ItemCode");
						String ItemName = json_data.getString("ItemName");
						String PurDesc = json_data.getString("PurDesc");
						String GroupCode = json_data.getString("GroupCode");
						String TypeCode = json_data.getString("TypeCode");
						String BrandCode = json_data.getString("BrandCode");
						String TaxComCode = json_data.getString("TaxComCode");
						String UnitCode = json_data.getString("UnitCode");
						String PackSize = json_data.getString("PackSize");
						String ReOrderLvl = json_data.getString("ReOrderLvl");
						String ReOrderQty = json_data.getString("ReOrderQty");
						String AvgPrice = json_data.getString("AvgPrice");
						String PrilCode = json_data.getString("PrilCode");
						String AddDate = json_data.getString("AddDate");
						String RecordId = json_data.getString("RecordId");
						String CatCode = json_data.getString("CatCode");
						String cosacc = json_data.getString("cosacc");
						String packing = json_data.getString("packing");
						String ItemStatus = json_data.getString("ItemStatus");
						String CurrentFreeQuantity = "0";
						//***********Check Free Items Qty*****************
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						
						Cursor cursorfreeQty = null;
						try {
							cursorfreeQty = mydb.query(FITEMFREQTY_TABLE,
									null, "ItemCode ='" + ItemCode.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (cursorfreeQty != null) {
							if (cursorfreeQty.getCount() > 0) {
								while (cursorfreeQty.moveToNext()) {
									CurrentFreeQuantity = cursorfreeQty.getString(2);
								}
							}
							else{
								CurrentFreeQuantity = "0";
							}
						}
						
						
						ContentValues newrowfItems = new ContentValues();
						Cursor newrowfItemListuserrows = null;
						try {
							newrowfItemListuserrows = mydb.query(FITEMS_TABLE,
									null,
									"ItemCode ='" + ItemCode.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfItemListuserrows != null) {
							if (newrowfItemListuserrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fItems (7)");
							} else {

								Log.v(TAG, "INSERT fItems(7) :" + i + "=" + ItemCode.trim());
								newrowfItems.put("ItemCode", ItemCode.trim());
								newrowfItems.put("ItemName", ItemName.trim());
								newrowfItems.put("BrandCode", BrandCode.trim());
								newrowfItems.put("TaxComCode",TaxComCode.trim());
								newrowfItems.put("PackSize", PackSize.trim());
								newrowfItems.put("ReOrderQty",ReOrderQty.trim());
								newrowfItems.put("AvgPrice", AvgPrice.trim());
								newrowfItems.put("PrilCode", PrilCode.trim());
								newrowfItems.put("AddDate", AddDate.trim());
								newrowfItems.put("packing", packing.trim());
								newrowfItems.put("RecordId", RecordId.trim());
								newrowfItems.put("PurDesc", PurDesc.trim());
								newrowfItems.put("TypeCode", TypeCode.trim());
								newrowfItems.put("UnitCode", UnitCode.trim());
								newrowfItems.put("ReOrderLvl", ReOrderLvl.trim());
								newrowfItems.put("CatCode", CatCode.trim());
								newrowfItems.put("cosacc", cosacc.trim());
								newrowfItems.put("GroupCode", GroupCode.trim());
								newrowfItems.put("itemsummary", ItemCode.trim()+ " " +ItemName.trim());
								newrowfItems.put("ItemStatus", ItemStatus.trim());
								newrowfItems.put("FreeItems", CurrentFreeQuantity);
								
								mydb.insert(FITEMS_TABLE, null, newrowfItems);
								newrowfItemListuserrows.close();
								mydb.close();
							}
						}
						
						newrowfItemListuserrows.close();
						mydb.close();

					}
					arrayLength = 8;//36
					progressHandler.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download FLocation details**************
			try {
				Log.e("", "Read URL 1: " + url);
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fLocations/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fLocationsResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String LocCode = json_data.getString("LocCode");
						String LocName = json_data.getString("LocName");
						String TeleNo = json_data.getString("TeleNo");
						String FaxNo = json_data.getString("FaxNo");
						String EMail = json_data.getString("EMail");
						String LoctCode = json_data.getString("LoctCode");
						String Contact = json_data.getString("Contact");
						String Address1 = json_data.getString("Address1");
						String Address2 = json_data.getString("Address2");
						String Address3 = json_data.getString("Address3");
						String AddUser = json_data.getString("AddUser");
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String RecordId = json_data.getString("RecordId");
						String prefix = json_data.getString("prefix");
						String cSettingsCode = json_data
								.getString("cSettingsCode");
						String ProfCen = json_data.getString("ProfCen");
						String cSettingsCde2 = json_data
								.getString("cSettingsCde2");
						String CostCode = json_data.getString("CostCode");
						String AccCode = json_data.getString("AccCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowflocation = new ContentValues();
						Cursor newrowflocationrows = null;
						try {
							newrowflocationrows = mydb.query(FLOCATION_TABLE,
									null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowflocationrows != null) {
							if (newrowflocationrows.getCount() >= 1) {
								Log.v(TAG, "Excisting FLocation(8)");
							} else {
								Log.v(TAG,
										"INSERT FLocation(8) :"
												+ RecordId.trim());
								newrowflocation.put("LocCode", LocCode.trim());
								newrowflocation.put("LocName", LocName.trim());
								newrowflocation.put("TeleNo", TeleNo.trim());
								newrowflocation.put("FaxNo", FaxNo.trim());
								newrowflocation.put("EMail", EMail.trim());
								newrowflocation
										.put("LoctCode", LoctCode.trim());
								newrowflocation.put("Contact", Contact.trim());
								newrowflocation
										.put("Address1", Address1.trim());
								newrowflocation
										.put("Address2", Address2.trim());
								newrowflocation
										.put("Address3", Address3.trim());
								newrowflocation.put("AddUser", AddUser.trim());
								newrowflocation.put("AddDate", AddDate.trim());
								newrowflocation.put("AddMach", AddMach.trim());
								newrowflocation
										.put("RecordId", RecordId.trim());
								newrowflocation.put("prefix", prefix.trim());
								newrowflocation.put("cSettingsCode",
										cSettingsCode.trim());
								newrowflocation.put("ProfCen", ProfCen.trim());
								newrowflocation.put("cSettingsCde2",
										cSettingsCde2.trim());
								newrowflocation
										.put("CostCode", CostCode.trim());
								newrowflocation.put("AccCode", AccCode.trim());
								mydb.insert(FLOCATION_TABLE, null,
										newrowflocation);
								newrowflocationrows.close();
								mydb.close();
							}
						}
						
						newrowflocationrows.close();
						mydb.close();
					}
					arrayLength = 4;//40
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download FSalRep Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FSalRep/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fSalRepResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String RepCode = json_data.getString("RepCode");
						String RepName = json_data.getString("RepName");
						String RepIdNo = json_data.getString("RepIdNo");
						String RepAdd1 = json_data.getString("RepAdd1");
						String RepAdd2 = json_data.getString("RepAdd2");
						String RepAdd3 = json_data.getString("RepAdd3");
						String RepTele = json_data.getString("RepTele");
						String RepMobil = json_data.getString("RepMobil");
						String RepEMail = json_data.getString("RepEMail");
						String AddUser = json_data.getString("AddUser");
						String AddMach = json_data.getString("AddMach");
						String AddDate = json_data.getString("AddDate");
						String RecordId = json_data.getString("RecordId");
						String RepPrefix = json_data.getString("RepPrefix");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowreaderfSalReprows = new ContentValues();
						Cursor newrowfSalReprows = null;
						try {
							newrowfSalReprows = mydb.query(FSALREP_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfSalReprows != null) {
							if (newrowfSalReprows.getCount() >= 1) {
								Log.v(TAG, "Excisting fSalRep (9)");
							} else {
								Log.v(TAG, "INSERT fSalRep(9) :" + i + "=" + RepCode.trim());
								newrowreaderfSalReprows.put("RepCode",
										RepCode.trim().toUpperCase());
								newrowreaderfSalReprows.put("RepName",
										RepName.trim());
								newrowreaderfSalReprows.put("RepIdNo",
										RepIdNo.trim());
								newrowreaderfSalReprows.put("RepAdd1",
										RepAdd1.trim());
								newrowreaderfSalReprows.put("RepAdd2",
										RepAdd2.trim());
								newrowreaderfSalReprows.put("RepAdd3",
										RepAdd3.trim());
								newrowreaderfSalReprows.put("RepTele",
										RepTele.trim());
								newrowreaderfSalReprows.put("RepMobil",
										RepMobil.trim());
								newrowreaderfSalReprows.put("RepEMail",
										RepEMail.trim());
								newrowreaderfSalReprows.put("AddUser",
										AddUser.trim());
								newrowreaderfSalReprows.put("AddMach",
										AddMach.trim());
								newrowreaderfSalReprows.put("AddDate",
										AddDate.trim());
								newrowreaderfSalReprows.put("RecordId",
										RecordId.trim());
								newrowreaderfSalReprows.put("RepPrefix",
										RepPrefix.trim());
								mydb.insert(FSALREP_TABLE, null,
										newrowreaderfSalReprows);
								newrowfSalReprows.close();
								mydb.close();
							}
						}
						
						newrowfSalReprows.close();
						mydb.close();
					}
					arrayLength = 4;//44
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fTaxDetResult Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FtaxDet/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fTaxDetResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String TaxComCode = json_data.getString("TaxComCode");
						String TaxCode = json_data.getString("TaxCode");
						String TaxRate = json_data.getString("TaxRate");
						String TaxMode = json_data.getString("TaxMode");
						String TaxSeq = json_data.getString("TaxSeq");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfTaxDet = new ContentValues();
						Cursor fTaxDetrows = null;
						try {
							fTaxDetrows = mydb.query(FTAXDET_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fTaxDetrows != null) {
							if (fTaxDetrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fTaxDet(10)");
							} else {
								Log.v(TAG, "INSERT fTaxDet(10) :" + i + "="
										+ RecordId.trim());
								newrowfTaxDet.put("TaxComCode",
										TaxComCode.trim());
								newrowfTaxDet.put("TaxCode", TaxCode.trim());
								newrowfTaxDet.put("TaxRate", TaxRate.trim());
								newrowfTaxDet.put("TaxMode", TaxMode.trim());
								newrowfTaxDet.put("TaxSeq", TaxSeq.trim());
								newrowfTaxDet.put("RecordId", RecordId.trim());
								mydb.insert(FTAXDET_TABLE, null, newrowfTaxDet);
								fTaxDetrows.close();
								mydb.close();
							}
						}
					
						fTaxDetrows.close();
						mydb.close();
					}
					arrayLength = 4;//48
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			// *****************Download fItemPri Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemPri/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemPriResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String PrilCode = json_data.getString("PrilCode");
						String Price = json_data.getString("Price");
						String ItemCode = json_data.getString("ItemCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfItemPri = new ContentValues();
						Cursor fItemPri = null;
						try {
							fItemPri = mydb.query(
									FITEMPRI_TABLE,
									null,
									"ItemCode ='" + ItemCode.trim()
											+ "' AND PrilCode ='"
											+ PrilCode.trim() + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (fItemPri != null) {
							if (fItemPri.getCount() >= 1) {
								Log.v(TAG, "Excisting fItemPri(11)");
							} else {
								Log.v(TAG, "Insert fItemPri(11):" + PrilCode);
								newrowfItemPri.put("PrilCode", PrilCode.trim());
								newrowfItemPri.put("Price", Price.trim());
								newrowfItemPri.put("ItemCode", ItemCode.trim());
								mydb.insert(FITEMPRI_TABLE, null,
										newrowfItemPri);
								fItemPri.close();
								mydb.close();
							}
						}
						
						fItemPri.close();
						mydb.close();
					}
					arrayLength = 6;//54
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fTax Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fTax/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace("{\"fTaxResult\":[{",
								"[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String TaxCode = json_data.getString("TaxCode");
						String TaxDevd = json_data.getString("TaxDevd");
						String TaxName = json_data.getString("TaxName");
						String TaxPayAcc = json_data.getString("TaxPayAcc");
						String TaxPer = json_data.getString("TaxPer");
						String TaxRecAcc = json_data.getString("TaxRecAcc");
						String TaxRegNo = json_data.getString("TaxRegNo");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfTax = new ContentValues();
						Cursor curfTax = null;
						try {
							curfTax = mydb.query(FTAX_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (curfTax != null) {
							if (curfTax.getCount() >= 1) {
								Log.v(TAG, "Excisting fTax(12)");
							} else {
								Log.v(TAG, "Insert fTax(12):" + TaxCode);
								newrowfTax.put("AddDate", AddDate.trim());
								newrowfTax.put("TaxCode", TaxCode.trim());
								newrowfTax.put("TaxDevd", TaxDevd.trim());
								newrowfTax.put("TaxDevd", TaxDevd.trim());
								newrowfTax.put("TaxName", TaxName.trim());
								newrowfTax.put("TaxPayAcc", TaxPayAcc.trim());
								newrowfTax.put("TaxPer", TaxPer.trim());
								newrowfTax.put("TaxRecAcc", TaxRecAcc.trim());
								newrowfTax.put("TaxRegNo", TaxRegNo.trim());
								newrowfTax.put("RecordId", RecordId.trim());
								mydb.insert(FTAX_TABLE, null, newrowfTax);
								curfTax.close();
								mydb.close();
							}
						}
					
						curfTax.close();
						mydb.close();
					}
					arrayLength = 4;//58
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fTaxHed Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fTaxHed/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fTaxHedResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String Active = json_data.getString("Active");
						String AddDate = json_data.getString("AddDate");
						String TaxComCode = json_data.getString("TaxComCode");
						String TaxComName = json_data.getString("TaxComName");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowftaxhed = new ContentValues();
						Cursor ftaxhed = null;
						try {
							ftaxhed = mydb.query(FTAXHED_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (ftaxhed != null) {
							if (ftaxhed.getCount() >= 1) {
								Log.v(TAG, "Excisting fTaxHedResult(13)");
							} else {
								Log.v(TAG, "Insert fTaxHedResult(13):"
										+ RecordId);
								newrowftaxhed.put("Active", Active.trim());
								newrowftaxhed.put("AddDate", AddDate.trim());
								newrowftaxhed.put("TaxComCode",
										TaxComCode.trim());
								newrowftaxhed.put("TaxComName",
										TaxComName.trim());
								newrowftaxhed.put("RecordId", RecordId.trim());
								mydb.insert(FTAXHED_TABLE, null, newrowftaxhed);
								ftaxhed.close();
								mydb.close();
							}
						}
						
						ftaxhed.close();
						mydb.close();
					}
					arrayLength = 4;//62
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fControl Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fControl/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fControlResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AdCntAcc = json_data.getString("AdCntAcc");
						String AutoAst = json_data.getString("AutoAst");
						String BalgCrLm = json_data.getString("BalgCrLm");
						String ComAdd1 = json_data.getString("ComAdd1");
						String ComAdd2 = json_data.getString("ComAdd2");
						String ComName = json_data.getString("ComName");
						String Comgainlos = json_data.getString("Comgainlos");
						String ContTxn = json_data.getString("ConfTxn");
						String CrosAccFlg = json_data.getString("CrosAccFlg");
						String DealCode = json_data.getString("DealCode");
						String IntegPrefx = json_data.getString("IntegPrefx");
						String IntegSeqNo = json_data.getString("IntegSeqNo");
						String NbtCmTaxNo = json_data.getString("NbtCmTaxNo");
						String RecordId = json_data.getString("RecordId");
						String SysId = json_data.getString("SysId");
						String Tranlock = json_data.getString("Tranlock");
						String VatCmTaxNo = json_data.getString("VatCmTaxNo");
						String aRetEarn = json_data.getString("aRetEarn");
						String basecur = json_data.getString("basecur");
						String comRegNo = json_data.getString("comRegNo");
						String comemail = json_data.getString("comemail");
						String comfax1 = json_data.getString("comfax1");
						String comgstac = json_data.getString("comgstac");
						String comtel1 = json_data.getString("comtel1");
						String comtel2 = json_data.getString("comtel2");
						String comweb = json_data.getString("comweb");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfcontrol = new ContentValues();
						Cursor curfcontrol = null;
						try {
							curfcontrol = mydb.query(FCONTROL_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (curfcontrol != null) {
							if (curfcontrol.getCount() >= 1) {
								Log.v(TAG, "Excisting RecordId(14)");
							} else {
								Log.v(TAG, "Insert RecordId(14):" + RecordId);
								newrowfcontrol.put("AdCntAcc", AdCntAcc.trim());
								newrowfcontrol.put("AutoAst", AutoAst.trim());
								newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
								newrowfcontrol.put("ComAdd1", ComAdd1.trim());
								newrowfcontrol.put("ComAdd2", ComAdd2.trim());
								newrowfcontrol.put("ComName", ComName.trim());
								newrowfcontrol.put("Comgainlos",
										Comgainlos.trim());
								newrowfcontrol.put("ContTxn", ContTxn.trim());
								newrowfcontrol.put("CrosAccFlg",
										CrosAccFlg.trim());
								newrowfcontrol.put("DealCode", DealCode.trim());
								newrowfcontrol.put("IntegPrefx",
										IntegPrefx.trim());
								newrowfcontrol.put("IntegSeqNo",
										IntegSeqNo.trim());
								newrowfcontrol.put("NbtCmTaxNo",
										NbtCmTaxNo.trim());
								newrowfcontrol.put("RecordId", RecordId.trim());
								newrowfcontrol.put("SysId", SysId.trim());
								newrowfcontrol.put("Tranlock", Tranlock.trim());
								newrowfcontrol.put("VatCmTaxNo",
										VatCmTaxNo.trim());
								newrowfcontrol.put("aRetEarn", aRetEarn.trim());
								newrowfcontrol.put("basecur", basecur.trim());
								newrowfcontrol.put("comRegNo", comRegNo.trim());
								newrowfcontrol.put("comemail", comemail.trim());
								newrowfcontrol.put("comfax1", comfax1.trim());
								newrowfcontrol.put("comgstac", comgstac.trim());
								newrowfcontrol.put("comtel1", comtel1.trim());
								newrowfcontrol.put("comtel2", comtel2.trim());
								newrowfcontrol.put("comweb", comweb.trim());
								mydb.insert(FCONTROL_TABLE, null,
										newrowfcontrol);
								curfcontrol.close();
								mydb.close();
							}
						}
					
						curfcontrol.close();
						mydb.close();
					}
					arrayLength = 4;//66
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			// ********************* Download FCompanyBranch Details
			// *******************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCompanyBranch/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FCompanyBranchResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCode = json_data.getString("cSettingsCode");
						String BranchCode = json_data.getString("BranchCode");
						String nNumVal = json_data.getString("nNumVal");
						String RecordId = json_data.getString("RecordId");
						String nMonth = json_data.getString("nMonth");
						String nYear = json_data.getString("nYear");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfbranch = new ContentValues();
						Cursor fCompanyBranch = null;
						try {
							fCompanyBranch = mydb.query(FCOMPANYBRANCH_TABLE,
									null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCompanyBranch != null) {
							if (fCompanyBranch.getCount() >= 1) {
								Log.v(TAG, "Excisting fCompanyBranch(15)");

							} else {
								Log.v(TAG, "Insert fCompanyBranch(15):"
										+ RecordId);
								newrowfbranch.put("cSettingsCodefb", cSettingsCode.trim());
								newrowfbranch.put("BranchCode", BranchCode.trim());
								newrowfbranch.put("nNumValfb", nNumVal.trim());
								newrowfbranch.put("RecordId", RecordId.trim());
								newrowfbranch.put("nMonthb", nMonth.trim());
								newrowfbranch.put("nYearb", nYear.trim());
								mydb.insert(FCOMPANYBRANCH_TABLE, null,
										newrowfbranch);
								fCompanyBranch.close();
								mydb.close();
							}
						}
						
						fCompanyBranch.close();
						mydb.close();
					}
					arrayLength = 4;//70
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// ********************* Download Fdebtax Details
			// *******************************//*
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/Fdebtax/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FdebtaxResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String DebCode = json_data.getString("DebCode");
						String RecordId = json_data.getString("RecordId");
						String TaxCode = json_data.getString("TaxCode");
						String TaxRegNo = json_data.getString("TaxRegNo");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfdebtax = new ContentValues();
						Cursor fDebTax = null;
						try {
							fDebTax = mydb.query(FDEBTAX_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fDebTax != null) {
							if (fDebTax.getCount() >= 1) {
								Log.v(TAG, "Excisting FdebtaxResult(16)");

							} else {
								Log.v(TAG, "Insert FdebtaxResult(16):"
										+ RecordId);
								newrowfdebtax.put("DebCode", DebCode.trim());
								newrowfdebtax.put("RecordId", RecordId.trim());
								newrowfdebtax.put("TaxCode", TaxCode.trim());
								newrowfdebtax.put("TaxRegNo", TaxRegNo.trim());
								mydb.insert(FDEBTAX_TABLE, null, newrowfdebtax);
								fDebTax.close();
								mydb.close();
							}
						}
						
						fDebTax.close();
						mydb.close();
					}
					arrayLength = 4;//74
					progressHandler.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// ********************* Download fCompanyDM Details
			// *******************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fCompanyDM/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCompanyDMResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCodedm = json_data
								.getString("cSettingsCode");
						String nMonth = json_data.getString("nMonth");
						String nYear = json_data.getString("nYear");
						String nNumVal = json_data.getString("nNumVal");
						String recordid = json_data.getString("recordid");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCompanyDM = new ContentValues();
						Cursor fCompanyDM = null;
						try {
							fCompanyDM = mydb.query(FCOMPANYDM_TABLE, null,
									"recordid ='" + recordid.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCompanyDM != null) {
							if (fCompanyDM.getCount() >= 1) {
								Log.v(TAG, "Excisting fCompanyDMResult(15)");

							} else {
								Log.v(TAG, "Insert fCompanyDMResult(15):"
										+ recordid);
								newrowfCompanyDM.put("cSettingsCodedm",
										cSettingsCodedm.trim());
								newrowfCompanyDM.put("nMonth", nMonth.trim());
								newrowfCompanyDM.put("nYear", nYear.trim());
								newrowfCompanyDM.put("nNumValdm",
										nNumVal.trim());
								newrowfCompanyDM.put("recordid",
										recordid.trim());
								mydb.insert(FCOMPANYDM_TABLE, null,
										newrowfCompanyDM);
								fCompanyDM.close();
								mydb.close();
							}
						}
						
						fCompanyDM.close();
						mydb.close();
					}
					arrayLength = 4;//78
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			
			/************Download fArea Table*****************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fArea/mobile123/"
											+ currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fAreaResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String AreaCode = json_data.getString("AreaCode");
						String AreaName = json_data.getString("AreaName");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfArea = new ContentValues();
						Cursor fAreaDetrows = null;
						try {
							fAreaDetrows = mydb.query(FAREA_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fAreaDetrows != null) {
							if (fAreaDetrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fArea(16)");
							} else {
								Log.v(TAG, "INSERT fArea(16) :" + i + "="
										+ RecordId.trim());
								newrowfArea.put("AddDate",AddDate.trim());
								newrowfArea.put("AddMach", AddMach.trim());
								newrowfArea.put("AddUser", AddUser.trim());
								newrowfArea.put("AreaCode", AreaCode.trim());
								newrowfArea.put("AreaName", AreaName.trim());
								newrowfArea.put("RecordId", RecordId.trim());
								try{
									ContentValues updateDebtor = new ContentValues();
									updateDebtor.put("AreaName", AreaName.trim());
									mydb.update(FDEBTOR_TABLE, updateDebtor, "AreaCode ='" + AreaCode + "'",
											null);
								}
								catch(Exception e){
									
								}
								
								mydb.insert(FAREA_TABLE, null, newrowfArea);
								fAreaDetrows.close();
								mydb.close();
							}
						}
						
						fAreaDetrows.close();
						mydb.close();
					}
					arrayLength = 4;//82
					progressHandler.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			
			/***********fDDBNote Table********************/

			try {
					DefaultHttpClient httpClient = new DefaultHttpClient();
					try {
						HttpResponse response = httpClient
								.execute(new HttpGet(
										connectionURL
												+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fddbnote/mobile123/"
												+ currentServerDbName));
					/*	HttpResponse response = httpClient
								.execute(new HttpGet("http://123.231.13.199:1025/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fddbnote/mobile123/BBM"));
						*/
						
						InputStream is = response.getEntity().getContent();
						if (is != null) {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(is, "iso-8859-1"), 8);
							sb = new StringBuilder();
							sb.append(reader.readLine() + "\n");
							String line = "0";

							while ((line = reader.readLine()) != null) {
								sb.append(line + "\n");
							}
							result = sb.toString();

							String FresultA = result.replace(
									"{\"fDdbNoteResult\":[{", "[{");
							FresultB = FresultA.replace("}]}", "}]");
							// convert String into InputStream
							isNew = new ByteArrayInputStream(FresultB.getBytes());

						}
						if (isNew != null) {
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(isNew, "iso-8859-1"), 8);
							sbNew = new StringBuilder();
							sbNew.append(reader.readLine() + "\n");
							String line = "0";
							while ((line = reader.readLine()) != null) {
								sbNew.append(line + "\n");
							}
							resultNew = sbNew.toString();
						}

						jArray = new JSONArray(resultNew);
						JSONObject json_data = null;
						for (int i = 0; i < jArray.length(); i++) {
							json_data = jArray.getJSONObject(i);
							String Amt = json_data.getString("Amt");
							String BAmt = json_data.getString("BAmt");
							String CurCode = json_data.getString("CurCode");
							String DebCode = json_data.getString("DebCode");
							String ManuRef = json_data.getString("ManuRef");
							String RecordId = json_data.getString("RecordId");
							String RefNo = json_data.getString("RefNo");
							String Remarks = json_data.getString("Remarks");
							String RepCode = json_data.getString("RepCode");
							String TotBal = json_data.getString("TotBal");
							String TxnDate = json_data.getString("TxnDate");

							mydb = openOrCreateDatabase(DBNAME,
									Context.MODE_PRIVATE, null);
							ContentValues newrowfddbnote = new ContentValues();
							Cursor fddbnoteDetrows = null;
							try {
								fddbnoteDetrows = mydb.query(FDDBNOTE_TABLE, null,
										"RecordId ='" + RecordId.trim() + "'",
										null, null, null, null);
							} catch (Exception e) {
							}
							if (fddbnoteDetrows != null) {
								if (fddbnoteDetrows.getCount() >= 1) {
									Log.v(TAG, "Excisting fddbnote(17)");
								} else {
									Log.v(TAG, "INSERT fddbnote(17) :" + i + "="
											+ RecordId.trim());
									newrowfddbnote.put("RefNo",RefNo.trim());
									newrowfddbnote.put("TxnDate", TxnDate.trim());
									newrowfddbnote.put("BAmt", BAmt.trim());
									newrowfddbnote.put("DebCode", DebCode.trim());
									newrowfddbnote.put("RecordId", RecordId.trim());
									newrowfddbnote.put("ManuRef", ManuRef.trim());
									newrowfddbnote.put("Curcode", CurCode.trim());
									newrowfddbnote.put("Amt", Amt.trim());
									newrowfddbnote.put("Totbal", TotBal.trim());
									newrowfddbnote.put("Remarks", Remarks.trim());
									newrowfddbnote.put("RepCode", RepCode.trim());
									mydb.insert(FDDBNOTE_TABLE, null, newrowfddbnote);
									fddbnoteDetrows.close();
									mydb.close();
								}
							}
							
							fddbnoteDetrows.close();
							mydb.close();
						}
						arrayLength = 4;//86
						progressHandler.sendMessage(progressHandler.obtainMessage());

					} catch (Exception e) {
						e.printStackTrace();
						Log.d("", "exception1 : " + e);
					}

				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Log.d("", "exception2 : " + e);
				}
			/************fBank Details************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient.execute(new HttpGet(
									connectionURL + "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fbank/mobile123/" + currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();
						String FresultA = result.replace("{\"fbankResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String Branch = json_data.getString("Branch");
						String RecordId = json_data.getString("RecordId");
						String bankaccno = json_data.getString("bankaccno");
						String bankadd1 = json_data.getString("bankadd1");
						String bankadd2 = json_data.getString("bankadd2");
						String bankcode = json_data.getString("bankcode");
						String bankname = json_data.getString("bankname");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfbank = new ContentValues();
						Cursor fbankDM = null;
						try {
							fbankDM = mydb.query(FBANK_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fbankDM != null) {
							if (fbankDM.getCount() >= 1) {
								Log.v(TAG, "Excisting fbankDM(18)");

							} else {
								Log.v(TAG, "Insert fbankDM(18):"+ RecordId);
								newrowfbank.put("AddDate",AddDate.trim());
								newrowfbank.put("AddMach", AddMach.trim());
								newrowfbank.put("AddUser", AddUser.trim());
								newrowfbank.put("Branch", Branch.trim());
								newrowfbank.put("RecordId",RecordId.trim());
								newrowfbank.put("bankaccno",bankaccno.trim());
								newrowfbank.put("bankadd1",bankadd1.trim());
								newrowfbank.put("bankadd2",bankadd2.trim());
								newrowfbank.put("bankcode",bankcode.trim());
								newrowfbank.put("bankname",bankname.trim());
								mydb.insert(FBANK_TABLE, null,newrowfbank);
								fbankDM.close();
								mydb.close();
							}
						}
						
						fbankDM.close();
						mydb.close();
					}
					arrayLength = 4;//90
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			

			
			/*****************fglfacc Details*******************/
			
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient.execute(new HttpGet(
									connectionURL + "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fglfacc/mobile123/" + currentServerDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();
						String FresultA = result.replace("{\"fglfaccResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);

						String AccCat = json_data.getString("AccCat");
						String AccCode = json_data.getString("AccCode");
						String AccDesc = json_data.getString("AccDesc");
						String AccTyp = json_data.getString("AccTyp");
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String BankChg = json_data.getString("BankChg");
						String ConAcc = json_data.getString("ConAcc");
						String CostCode = json_data.getString("CostCode");
						String CurCode = json_data.getString("CurCode");
						String NoteCode = json_data.getString("NoteCode");
						String NumGen = json_data.getString("NumGen");
						String RecordId = json_data.getString("RecordId");
						String SortCode = json_data.getString("SortCode");
						String SubnNote = json_data.getString("SubnNote");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfglfacc = new ContentValues();
						Cursor newrowfglfaccDM = null;
						try {
							newrowfglfaccDM = mydb.query(FGLFACC_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfglfaccDM != null) {
							if (newrowfglfaccDM.getCount() >= 1) {
								Log.v(TAG, "Excisting newrowfglfaccDM(19)");

							} else {
								Log.v(TAG, "Insert newrowfglfaccDM(19):"+ RecordId);
						        newrowfglfacc.put("AccCat",AccCat.trim());
								newrowfglfacc.put("AccCode",AccCode.trim());
								newrowfglfacc.put("AccDesc",AccDesc.trim());
								newrowfglfacc.put("AccTyp",AccTyp.trim());
								newrowfglfacc.put("AddDate",AddDate.trim());
								newrowfglfacc.put("AddMach",AddMach.trim());
								newrowfglfacc.put("AddUser",AddUser.trim());
								newrowfglfacc.put("BankChg",BankChg.trim());
								newrowfglfacc.put("ConAcc",ConAcc.trim());
								newrowfglfacc.put("CostCode",CostCode.trim());
								newrowfglfacc.put("CurCode",CurCode.trim());
								newrowfglfacc.put("NoteCode",NoteCode.trim());
								newrowfglfacc.put("NumGen",NumGen.trim());
								newrowfglfacc.put("RecordId",RecordId.trim());
								newrowfglfacc.put("SortCode",SortCode.trim());
								newrowfglfacc.put("SubnNote",SubnNote.trim());
								
								mydb.insert(FGLFACC_TABLE, null,newrowfglfacc);
								newrowfglfaccDM.close();
								mydb.close();
							}
						}
						
						newrowfglfaccDM.close();
						mydb.close();
					}
					arrayLength = 4;//94
					progressHandler.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (NetFail == 0) {
				mProgressDialog.dismiss();
				// arrayLength = 100;
				try {
					showDialog(DIALOG_SYNC_SUCCESS);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (NetFail == 404) {
				countDownActivator();
			}

		}

	}

	// handler for the background updating
	Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.v(TAG, "Array Length XXX :" + arrayLength);
			mProgressDialog.incrementProgressBy(arrayLength);
		}
	};

	protected void UpdateUserSettings() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			ContentValues user = new ContentValues();
			user.put("username", "admin");
			user.put("lrepprefix", "");
			user.put("lreploccode", "");
			user.put("currentStOrdNo", "");
			user.put("locationCode", "");
			user.put("receiptCode", "");
			user.put("serverDbName", serverDbName);
			user.put("printerMac", "00:22:58:3A:C6:49");
			user.put("repareacode", "");
			user.put("repdealcode", "");
			user.put("reproutecode", "");
			mydb.insert(USER_SETTINGS, null, user);
		} catch (Exception e) {
		}
	}

	private String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}

	private String uncompressInputStream(InputStream inputStream)
			throws IOException {
		StringBuilder value = new StringBuilder();

		GZIPInputStream gzipIn = null;
		InputStreamReader inputReader = null;
		BufferedReader reader = null;

		try {
			gzipIn = new GZIPInputStream(inputStream);
			inputReader = new InputStreamReader(gzipIn, "UTF-8");
			reader = new BufferedReader(inputReader);

			String line = "";
			while ((line = reader.readLine()) != null) {
				value.append(line + "\n");
			}
		} finally {
			try {
				if (gzipIn != null) {
					gzipIn.close();
				}

				if (inputReader != null) {
					inputReader.close();
				}

				if (reader != null) {
					reader.close();
				}

			} catch (IOException io) {

				io.printStackTrace();
			}

		}

		return value.toString();
	}

	private void displayCurrentSettings() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor curUserSettings = null;
		try {
			curUserSettings = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}

		if (curUserSettings != null) {
			if (curUserSettings.getCount() >= 1) {
				while (curUserSettings.moveToNext()) {
					CurrentUser = curUserSettings.getString(1);
					String lrepprefix = curUserSettings.getString(2);
					String lreploccode = curUserSettings.getString(3);
					String locationCode = curUserSettings.getString(5);
					String receiptCode = curUserSettings.getString(6);
					String serverDbName = curUserSettings.getString(7);
					String printerMac = curUserSettings.getString(8);
					String repareacode = curUserSettings.getString(9);
					String repdealcode = curUserSettings.getString(10);
					String reproutecode = curUserSettings.getString(11);

					etsettingssdb.setText(serverDbName);
					etsettingsrepprefix.setText(lrepprefix);
					etsettingsprintermac.setText(printerMac);
					etsettingsuser.setText(CurrentUser);
					etsettingsrepcode.setText(CurrentUser);
					etsettingslocationcode.setText(lreploccode);
					etsettingsareacode.setText(repareacode);
					etsettingsdealcode.setText(repdealcode);
					etsettingsroutecode.setText(reproutecode);
				}
			}
		}
	}

	public void checkNetwork() {
		// TODO Auto-generated method stub
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			Log.v(TAG, "Net Work Present........");
			NetFail = 0;
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			// showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
			// "You don't have internet connection.", false);
			Log.v(TAG, "Net Work Disabled........");
			NetFail = 404;
			countDownActivator();
		}
	}

	private void countDownActivator() {
		// TODO Auto-generated method stub
		mCountDown = new CountDownTimer(30000, 1000) {

			@Override
			public void onFinish() {
				mProgressDialog.dismiss();
				showAlertDialog(
						DM_BBM_Settings.this,
						"Internet Connection Lost..",
						"Your Internet Connection Lost During Syncing.Data Sync Not Completed. Tap OK to Continue Sync..",
						false);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v(TAG, "Time Remaining Chk 1:" + millisUntilFinished / 1000);
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					NetFail = 0;
					arrayLength = 0;
					// Internet Connection is Present
					// Stop coun down
					mCountDown.cancel();
				} else {
					// Internet connection is not present

				}
			}
		}.start();
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	@SuppressLint("SimpleDateFormat")
	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("dd/MM/yyyy");
		String date_to_string = ddMMMyyFormat.format(dateNow);
		return date_to_string;
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_SYNC_SUCCESS:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_bbm_dialog_sync_success, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Sync Data Completed. Select SalesRef...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		}
		return InvoiceHeaderAlert;
	}
}
